package com.szly.phm.admin.config;

import com.szly.phm.admin.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.firewall.StrictHttpFirewall;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description : ${创建类}
 * @Author : chengjiang
 * @Date: 2021/7/2 15:56
 */
@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    // 用户登录认证处理器
    @Autowired
    private UserLoginHandler userLoginHandler;

    // 登录成功处理器
    @Autowired
    private JEJLLoginSuccessHandler jejlLoginSuccessHandler;

    // 登出成功处理器
    @Autowired
    private JEJLLogoutSuccessHandler jejlLogoutSuccessHandler;

    // 未登录处理器
    @Autowired
    private JEJLNotLoginHandler jejlNotLoginHandler;

    // 登录失败处理器
    @Autowired
    private JEJLLoginFailHandler jejlLoginFailHandler;

    // token过滤器
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Value("${com.phm.token.antMatchers}")
    private String antMatchers;


    // 解决无法直接注入 AuthenticationManager
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 自定义用户登录认证接口
    @Override
    protected void configure(AuthenticationManagerBuilder auth) {

        auth.authenticationProvider(userLoginHandler);
    }

    // 配置Security的核心控制逻辑
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // CSRF禁用，因为不使用session
        httpSecurity.cors().and().csrf().disable();
        httpSecurity
                // 过滤请求
                .authorizeRequests()
                // 不需要认证的接口路径
                .antMatchers(antMatchers.split(",")).permitAll()
                // 其他的都需要认证后才能访问
                .anyRequest().authenticated().and()
                // 未登录处理器
                .httpBasic().authenticationEntryPoint(jejlNotLoginHandler).and()
                // 配置登录地址路径以及参数名
                .formLogin()
                .loginProcessingUrl("/pc/v1/login")
                // 登录成功处理器
                .successHandler(jejlLoginSuccessHandler)
                // 登录失败处理器
                .failureHandler(jejlLoginFailHandler).and()
                // 配置登出地址路径
                .logout().logoutUrl("/pc/v1/logout")
                // 登出成功处理器
                .logoutSuccessHandler(jejlLogoutSuccessHandler)
                .and()
                .exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint());
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 基于token，所以不需要session
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 添加token过滤器
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedDoubleSlash(true);
        firewall.setAllowBackSlash(true);
        super.configure(web);
    }
}
